import React, { useEffect, useState } from 'react';
import { Button, Drawer, Form, Input, Modal, Popconfirm, Space, Table, Tag } from 'antd';
import type { FormProps, TableProps } from 'antd';
import request from '../../api/request';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

function Index() {

    const [data,setData]=useState([])

    const [count,setCount]=useState(0)
    const [page,setPage]=useState(1)
    const [pageSize,setpageSize]=useState(10)

    const [title1,setTitle1]=useState('')
    const [form]=Form.useForm()

    const [edit,setEdit]=useState()

    // 获取列表数据
    const getData=()=>{
        request.get('/api/article/list',{
            params:{
                page:page,
                pageSize:pageSize
            }
        }).then((res)=>{
            console.log(res);
            setData(res.data.rows)
            setCount(res.data.count)
        })
    }
    useEffect(()=>{
        getData()
    },[page,pageSize])


    // 点击新增按钮
    const add=()=>{
        setOpen(true);
        setTitle1('新增')
        form.resetFields()
    }

    // 点击编辑按钮
    const bj=(record)=>{
        setOpen(true);
        setTitle1('编辑')
        form.setFieldsValue(record)
        setEdit(record.id)
    }

    // 控制弹框状态
    const [open, setOpen] = useState(false);

  const onClose = () => {
    setOpen(false);
  };


    // 弹框表单提交
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
  console.log('Success:', values);
  if(title1=='新增'){
    request.post('/api/article',{
        "title":values.title,//文章标题
        "content":values.content,//文章内容
        "tagList":["HTTP"],//标签  array[string]
        "categoryList":["HTTP"],//分类  array[string]
        "authorId":47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息

    }).then((res)=>{
        getData()
        setOpen(false);
        alert('新增成功')
    })
  }else if(title1=='编辑'){
    request.put(`/api/article/${edit}`,{...values,id:edit}).then((res)=>{
        getData()
        setOpen(false);
        alert('编辑成功')
    })
  }
};

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

// 删除
const del=(record)=>{
    setData(data.filter((item)=>item.id!=record.id))
    alert('删除成功')
}

// 批量删除
 const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
 const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const alldel=()=>{
    setData(data.filter((item)=>!selectedRowKeys.includes(item.id)))
    alert('删除成功')
  }

//   搜索
const { Search } = Input;

const onSearch= (value) =>{
    request.get('/api/article/list',{
        params:{
            keyword:value,
        }
    }).then((res)=>{
        setData(res.data.rows)
    })
};


    const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    render: (text) => <a>{text}</a>,
  },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: '内容',
    dataIndex: 'content',
    key: 'content',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
  },
  {
    title: '标签',
    key: 'tags',
    dataIndex: 'tags',
    render: (_, { tags }) => (
      <>
        {tags.map((tag) => {
          return (
            <Tag key={tag.name}>
              {tag.name.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
  },
  {
    title: 'Action',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
         <Button color="primary" variant="outlined" onClick={()=>bj(record)}>编辑</Button>
         
          <Popconfirm title="确定删除吗?" onConfirm={()=>del(record)}>
            <Button color="danger" variant="outlined">删除</Button>
          </Popconfirm>
      </Space>
    ),
  },
];


  return (
    <div>
        {/* 顶部操作表单 */}
         <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
        >
             <Search placeholder="input search text" onSearch={onSearch} style={{ width: 200 }} />
            <Button color="primary" variant="solid" onClick={add}>新增</Button>
            <Button color="danger" variant="solid" onClick={alldel}>批量删除</Button>
        </Form>

        {/* 弹框 */}
        <Drawer
        title={title1}
         closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
         <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
        >
            <Form.Item
            label='标题'
            name='title'
            rules={[{ required: true, message: '标题不能为空' }]}
            >
            <Input />
            </Form.Item>

            <Form.Item
            label='文章内容'
            name='content'
            rules={[{ required: true, message: '内容不能为空' }]}
            >
            <Input />
            </Form.Item>

            <Form.Item label={null}>
                <Button type="primary" htmlType="submit">
                    确定
                </Button>
            </Form.Item>

        </Form>
        
      </Drawer>


      <Table rowSelection={rowSelection}
      rowKey={'id'}
       columns={columns}
        dataSource={data} 
      pagination={{
        total:count,
        onChange(page,pageSize){
            setPage(page)
            setpageSize(pageSize)
        },
        showSizeChanger:true,
        showQuickJumper:true,
        showTotal:total=> `Total ${total} items`
      }}
      />
    </div>
  )
}

export default Index
